<?php

namespace App\Http\Service\Baoliao;

use App\Models\Baoliaopost;
use App\Models\Baoliaolike;
use App\Models\Baoliaocollect;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use App\Http\Service\BaseService;
use App\Http\Service\ContentScoringService;
use App\Models\Baoliaolog;
use App\Http\Service\UserService;
use App\Http\Service\MoneyService;
use App\Http\Service\PlatformsService;
use App\Http\Service\SiteConfigService;
use App\Http\Service\PostaiService;
use App\Http\Service\Brand\CategorymappingService;
use App\Http\Service\Brand\BrandmappingService;
use App\Models\Doubanpostproduct;
use App\Models\Doubanpost;
use App\Http\Service\Douban\DoubanpostproductService;
class BaoliaoService  extends BaseService
{
    private $url;
    private $getInfo;
    private $model;
    public $URL_MAP;
    public function __construct(Baoliaopost $model,Baoliaolog $baoliaolog,UserService  $userService,PlatformsService $platformsService,SiteConfigService $siteConfigService,Doubanpostproduct $doubanpostproduct,DoubanpostproductService $DoubanpostproductService,PostaiService $postaiService,Doubanpost $doubanpost,MoneyService $moneyService,CategorymappingService $categorymappingService,BrandmappingService $brandmappingService)
    {
        parent::__construct();
        $this->model = $model;
        $this->userService=$userService;
        $this->platformsService=$platformsService;
        $this->baoliaolog=$baoliaolog;
        $this->siteConfigService=$siteConfigService;
        $this->doubanpostproduct=$doubanpostproduct;
        $this->DoubanpostproductService=$DoubanpostproductService;
        $this->url=config('myurl.link-batch-parse.url');
        $this->getInfo=config('myurl.getInfo');
        $this->URL_MAP=config('myurl.URL_MAP');
        $this->postaiService=$postaiService;
        $this->doubanpost=$doubanpost;
        $this->moneyService=$moneyService;
        $this->categorymappingService=$categorymappingService;
        $this->brandmappingService=$brandmappingService;

    }
    //爆料信息上传-机器人-添加
    public function perfectInfo3($request,$data=[])
    {
        $jsonData = $request->json()->all();
        $data['json_data']=json_encode($jsonData, JSON_UNESCAPED_UNICODE);
        $unique_id=$data['unique_id'];
        #dd($unique_id);
        #$unique_id=
        #补全时间格式
        $data['start_time']=completeDateTime($data['start_time']);
        $data['end_time']=completeDateTime($data['end_time']);
        #判断爆料数据是否已经能爆料
        #获取最近一条数据


        $where=[
            'platform_name'=>$data['platform_name'],
            'product_unique_id'=>$data['product_unique_id'],
            'is_expired'=>2
        ];
        #dd($where);
        #重新整理下划线
        $first=$this->model->where($where)->orderBy('id', 'desc')->first();

        if($first){
            $data['update_time'] =date("Y-m-d H:i:s");
            #dd($data['is_expired']);
            // 获取当前时间
            $currentTime =  time();
           // dd($first['end_time']);
            // 判断是否显示警告
            if ($currentTime >= strtotime($first['start_time']) && 
                $currentTime <= strtotime($first['end_time'])){
                //商品未过期
                $this->error("该商品已被其他人爆料,可以去评论【{$first['id']}】");
            }else{
                $id=$first['id'];
                $data3=[];
                $data3['create_time'] =date("Y-m-d H:i:s");
                $data3['is_expired'] =1;//过期
                $this->model->where(['id'=>$id])->update($data3);
            }

            ///die("sdfsd");
            #$res=1;
            #$res=$this->model->where(['unique_id'=>$unique_id])->update($data);
            $res=$post_id=$this->model->insertGetId($data);
        }else{
            #修改默认值
            $type=$data['type'];

            $siteConfig=$this->siteConfigService->getList('4');
            $view_count=$siteConfig['content']['view_count'];


            if(in_array($type,['2','4'])){
                $min=$siteConfig['content']['min'];
                $max=$siteConfig['content']['max'];
                $data['view_count'] =getRandomInRange($min,$max);
            }

            if(empty($data['view_count'])){
                $data['view_count'] =0;
            }
            #测试
            #$data['view_count'] =1200;
            #添加数据
            $data['create_time'] =date("Y-m-d H:i:s");
            $data['update_time'] =date("Y-m-d H:i:s");

            $res=$post_id=$this->model->insertGetId($data);



        }
       
        
        
        //dd($data);
        
       
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }

    //爆料完善信息-添加
    public function perfectInfo($request,$data=[])
    {
/*        爆料和逛逛当天24点结束（优惠不一定会过期，只是其他人可以重新发布这个商品的爆料了），比如一个商品(平台+商品id)在今天有人上传了，那么到24点之前再有人上传，则提示该商品已被其他人爆料，引导去评论 过了24点后，这个商品可以重新被爆料上传*/

        $jsonData = $request->json()->all();
        $data['json_data']=json_encode($jsonData, JSON_UNESCAPED_UNICODE);
        $platform_name=$data['platform_name'];
        $product_unique_id=$data['product_unique_id'];

        
        $first=$this->model->where(['platform_name'=>$platform_name,'product_unique_id'=>$product_unique_id,'is_expired'=>2])->orderBy('id', 'desc')->first();
        if($first){
            // 获取当前时间
            $currentTime =  time();

            // 判断是否显示警告
            if ($currentTime >= strtotime($first['start_time']) && 
                $currentTime <= strtotime($first['end_time'])){
                //商品未过期
                $this->error("该商品已被其他人爆料,可以去评论");
            }else{
                $id=$first['id'];
                $data3=[];
                $data3['create_time'] =date("Y-m-d H:i:s");
                $data3['is_expired'] =1;//过期
                $this->model->where(['id'=>$id])->update($data3);
            }

        }
        #判断上传的帖子的开始时间和结束时间  结束时间不能小于发布时间
        $currentTime =  time();
        if ($currentTime < strtotime($data['start_time']) || 
            $currentTime > strtotime($data['end_time'])){
            //商品未过期
            $this->error("[开始时间和结束时间已经结束]结束时间不能小于发布时间");
        }
        #修改默认值
        $type=$data['type'];
        $siteConfig=$this->siteConfigService->getList('4');
        $view_count=$siteConfig['content']['view_count'];
        if(in_array($type,['2','4'])){
            $min=$siteConfig['content']['min'];
            $max=$siteConfig['content']['max'];
            $data['view_count'] =getRandomInRange($min,$max);
        }
        if(empty($data['view_count'])){
            $data['view_count'] =0;
        }
        
        //dd($data);
        
        #添加数据
        $data['create_time'] =date("Y-m-d H:i:s");
        $data['update_time'] =date("Y-m-d H:i:s");

        $res=$post_id=$this->model->insertGetId($data);


        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }
    //爆料数组传参
    public function perfectInfoParms3($request,$data_baoliao_post)
    {
        $type=$data_baoliao_post['type'];
        if(empty($type)){
            $type=5;
        }
        #用户id
        $user_id=$data_baoliao_post["user_id"];
        $avatar="";
        $nickname="";
        if(!empty($user_id) && $user_id>=1000){
           $user_info=$this->userService->update_user($user_id);
           $nickname=$user_info['nickname'];
           $avatar=$user_info['avatar'];
           
        }
        

        $purchase=[];
        $purchase_steps=[];
        $purchase_youhuiquan=$data_baoliao_post["purchase_youhuiquan"];
        $purchase_huodong=$data_baoliao_post["purchase_huodong"];
        $purchase_jiagou=$data_baoliao_post["purchase_jiagou"];
        $purchase_coudan=$data_baoliao_post["purchase_coudan"];

        if(!empty($purchase_youhuiquan)){
            $purchase_steps=array_merge($purchase,$purchase_youhuiquan);
        }
        if(!empty($purchase_huodong)){
            $purchase_steps=array_merge($purchase_steps,$purchase_huodong);
        }
        if(!empty($purchase_jiagou)){
            $purchase_steps=array_merge($purchase_steps,$purchase_jiagou);
        }
        if(!empty($purchase_coudan)){
            $purchase_steps=array_merge($purchase_steps,$purchase_coudan);
        }
        //佣金比例
        $commission_rate=$data_baoliao_post["commission_rate"];
        if(empty($commission_rate)){
            $commission_rate=0.00;
        }
        $commission_rate=$commission_rate*100;
        //数量
        $quantity=$data_baoliao_post["quantity"];
        if(empty($quantity)){
            $quantity=1;
        }
        //单价
        $unit_price=$data_baoliao_post["unit_price"];
        if(empty($unit_price)){
            $unit_price=1;
        }
        //下单价
        $final_price=$unit_price*$quantity;
        //佣金金额
        $commission_amount=$data_baoliao_post["commission_amount"];
        //佣金总金额
        $commission_amount_total=$commission_amount*$quantity;

        $category_id=$data_baoliao_post["category_id"];
        $category_name=$data_baoliao_post["category_name"];
        $platform=$data_baoliao_post["platform"];
        //dd($platform);
        $productId=$data_baoliao_post["product_id"];
        //dd($productId);
        if($productId){
            $is_product=1;
        }
        //dd($platform);
        //测试京东
        //$platform='拼多多';
        //$productId='E9L2lYP4BSBHtvaxwfjfHwEH8luiqAiApA_JkqttchhD';

        if(!isset($this->URL_MAP[$platform])){
            $this->error("平台不存在,请联系管理员添加平台[{$platform}]");
        }
        $url=$this->URL_MAP[$platform];
        $product_list=[];
        if($url){
            //是否是产品
            $fetch_platform_data=fetch_platform_data($platform,$productId,$url);

            
            if($fetch_platform_data){
                $product_list[]=[
                    'type'=> 'link',
                    'text'=> $fetch_platform_data['productUrl'],
                    'title'=> $fetch_platform_data['title'],
                    'productImage'=> $fetch_platform_data['productImage'],
                    'productName'=> $fetch_platform_data['productName'],
                    'product_id'=> $fetch_platform_data['item_id'],
                    'platform_name'=> $platform,
                    'link_text'=> '',
                ];

            }else{
                $is_product=0;
            }
        }



        $purchase_screenshots=[];
        $purchase_screenshots=$data_baoliao_post["purchase_screenshots"];

        $purchase_screenshots=array_filter($purchase_screenshots);
        $purchase_screenshots=array_unique($purchase_screenshots);
        //dd($purchase_screenshots);

        $image=[];
        $images=$data_baoliao_post["images"];
        $images=array_filter($images);
        $images=array_unique($images);

        $product_unique_id=$data_baoliao_post["product_unique_id"];
        if(empty($product_unique_id)&&$productId){
            $ar=platform_name_product_id($platform,$productId);
            $product_unique_id=$ar['1'];
           
        }
        if(empty($product_unique_id)){
            $this->error("product_unique_id 不能为空");
        }
        $start_time=$data_baoliao_post["start_time"];
        $end_time=$data_baoliao_post["end_time"];

        #重新组装 unique_id
        $start_times=strtotime($start_time);
        $end_times=strtotime($end_time);
        if($end_times<$start_times){
            $this->error("结束时间不能大于开始时间");
        }
        if(empty($platform)){
            $this->error("平台[platform]不能为空");
        }
        $uniqid=uniqid() . '_' . time();
        #机器人上传数据唯一性判断  (后缀+平台)
        $unique_id="{$product_unique_id}_{$platform}";
        $unique_id=$uniqid;
        #判断帖子是否过期
        $is_expired = checkExpired($start_times, $end_times);
        //dd($is_expired);

        # title  值选替换星选
        $title=$data_baoliao_post["title"];
        $title=str_replace('值选', '星选', $title);
        #是否有官方补贴
        $is_subsidy=2;
        $is_subsidy_=["is_subsidy"];
        if(!empty($is_subsidy_)){
            $is_subsidy=$is_subsidy_;
        }

        $data=[
            'unique_id'=>$unique_id,
            'is_product'=>$is_product,
            'purchase_steps'=>$purchase_steps,
            'title'=>$title,
            'platform_name'=>$platform,
            'start_time'=>$start_time,
            'article_title'=>$data_baoliao_post["article_title"],
            'brand_name'=>$data_baoliao_post["brand_name"],
            'end_time'=>$end_time,
            'content'=>$data_baoliao_post["content"],
            'cover'=>$data_baoliao_post["cover"],
            'product_id'=>$productId,
            'unit_price'=>$unit_price,
            'quantity'=>$quantity,
            'final_price'=>$final_price,
            'commission_amount_total'=>$commission_amount_total,
            'images'=>$images,
            'purchase_screenshots'=>$purchase_screenshots,
            'category_id'=>$category_id,
            'category_name'=>$category_name,
            'origain_price'=>$data_baoliao_post["origain_price"],
            'commission_rate'=>$commission_rate,
            'commission_amount'=>$commission_amount,//佣金金额
            'shop_id'=>$data_baoliao_post["shop_id"],
            'product_unique_id'=>$product_unique_id,
            'product_list'=>$product_list,
            'type'=>$type, //2用户添加数据  3.机器人推动数据
            'publish_time'=>date("Y-m-d H:i:s"),
            'is_expired'=>$is_expired,
            'user_id'=>$user_id,
            'avatar'=>$avatar,
            'nickname'=>$nickname,
            'subsidy_rate'=>$data_baoliao_post["subsidy_rate"],
            'subsidy_amount'=>$data_baoliao_post["subsidy_amount"],
            'subsidy_name'=>$data_baoliao_post["subsidy_name"],
            'is_subsidy'=>$is_subsidy,
            'view_count'=>0,//ai 默认浏览量
            'sales_count'=>0,
            'like_count'=>0,
            'jd_plus_commission_desc'=>$data_baoliao_post["jd_plus_commission_desc"],
            'original_brand_name'=>$data_baoliao_post["original_brand_name"],
            'standard_brand_name'=>$data_baoliao_post["standard_brand_name"],
            'original_category_name'=>$data_baoliao_post["original_category_name"],
            'standard_category_name'=>$data_baoliao_post["standard_category_name"],

        ];

       
 

        //dd($data);

        $platform_name=$data['platform_name'];
        //活动，优惠，加购，凑单，下单
        $purchase_steps=$data['purchase_steps'];
        #组装数据
        foreach ($purchase_steps as $k=> &$v) {
            switch ($v['type']) {
                case '1':
                    $v['data-dimension122']="优惠券";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                case '2':
                    if(isset($v['link'])&&empty($v['link'])){
                        unset($purchase_steps[$k]);
                    }else{
                        $v['data-dimension122']="活动";
                        $v['tag_text']=$v['description'];
                        $v['you_hui_tiao_zhuan_link_end']='';
                        $v['huo_dong_time']='';
                    }
                    
                    break;
                case '3':
                    $v['data-dimension122']="加购";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                case '4':
                    $v['data-dimension122']="凑单";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                default:
            }


        }

        $link="";
        if(!empty($data['product_list'])){
            $link=$data['product_list'][0]['text'];
        }
        //dd($data['product_list']);
        //加购
        $purchase_steps[]=[
            "data-dimension122"=> "加购",
            "type"=>3,
            "tag_text"=> "下单{$quantity}件-{$data['title']}",
            "you_hui_tiao_zhuan_link_end"=> "",
            "huo_dong_time"=> null,
            "platform"=>$platform_name,
            "title"=> "加购",
            "description"=> "下单{$quantity}件-{$data['title']}",
            "link"=>$link,

        ];

        //下单
        if($quantity>1){

            $lastunitPrice = $unit_price-$commission_amount;
            //dd($commission_amount);
            //$shifu=$unit_price*$quantity;
            $lastunitPrice =_round($lastunitPrice);
            $purchase_steps[]=[
                "data-dimension122"=> "下单",
                "title"=> "下单",
                "type"=> 5,
                "description"=> "下单{$quantity}件实付{$final_price}，下单后返利约{$commission_amount_total}元，单价合{$lastunitPrice}元",
                "link"=>'',
                "platform"=>'',
            ];
        }else{
            $purchase_steps[]=[
                "data-dimension122"=> "下单",
                "type"=> 5,
                "title"=> "下单",
                "description"=> "实付{$final_price}，下单后返利约{$commission_amount_total}元",
                "link"=>'',
                "platform"=>'',
            ];
        }

        //dd($purchase_steps);
        //die("6666");



        #爆料修改默认值--添加帖子的时候

            
        //dd($data);
        $data['purchase_steps'] = json_encode($purchase_steps, JSON_UNESCAPED_UNICODE);

        $data['images'] = json_encode($data['images'], JSON_UNESCAPED_UNICODE);
        $data['purchase_screenshots'] = json_encode($data['purchase_screenshots'], JSON_UNESCAPED_UNICODE);
        
        
        $data['product_list'] = json_encode($data['product_list'], JSON_UNESCAPED_UNICODE);



        $jsonData = $data_baoliao_post;
        $data['json_data']=json_encode($jsonData, JSON_UNESCAPED_UNICODE);
        $unique_id=$data['unique_id'];
        #dd($unique_id);
        #$unique_id=
        #补全时间格式
        $data['start_time']=completeDateTime($data['start_time']);
        $data['end_time']=completeDateTime($data['end_time']);
        #判断爆料数据是否已经能爆料
        #获取最近一条数据


        $where=[
            'platform_name'=>$data['platform_name'],
            'product_unique_id'=>$data['product_unique_id'],
            'is_expired'=>2
        ];
        #dd($where);
        #重新整理下划线
        $first=$this->model->where($where)->orderBy('id', 'desc')->first();
        $baoliao_hb=[];
        
        if($first){
            $data['update_time'] =date("Y-m-d H:i:s");
            #dd($data['is_expired']);
            // 获取当前时间
            $currentTime =  time();
           // dd($first['end_time']);
            // 判断是否显示警告
            if ($currentTime >= strtotime($first['start_time']) && 
                $currentTime <= strtotime($first['end_time'])){
                //商品未过期
                return("该商品已被其他人爆料,可以去评论【{$first['id']}】");
            }else{
                $id=$first['id'];
                $data3=[];
                $data3['create_time'] =date("Y-m-d H:i:s");
                $data3['is_expired'] =1;//过期
                $this->model->where(['id'=>$id])->update($data3);
            }

            ///die("sdfsd");
            #$res=1;
            #$res=$this->model->where(['unique_id'=>$unique_id])->update($data);
            $res=$post_id=$this->model->insertGetId($data);
        }else{
            #修改默认值
            $type=$data['type'];

            $siteConfig=$this->siteConfigService->getList('4');
            $view_count=$siteConfig['content']['view_count'];


            if(in_array($type,['2','4'])){
                $min=$siteConfig['content']['min'];
                $max=$siteConfig['content']['max'];
                $data['view_count'] =getRandomInRange($min,$max);
            }

            if(empty($data['view_count'])){
                $data['view_count'] =0;
            }
            #测试
            #$data['view_count'] =1200;
            #添加数据
            $data['create_time'] =date("Y-m-d H:i:s");
            $data['update_time'] =date("Y-m-d H:i:s");

            $res=$post_id=$this->model->insertGetId($data);



        }
       // dd($res);
       $first_data=$this->model->where(['id'=>$res])->first();
        
       $baoliao_hb[]=[
            "unit_price"=> $first_data['unit_price'],
            "publish_time"=> $first_data['publish_time'],
            "commission_rate"=> $first_data['commission_rate'],
            "commission_amount"=> $first_data['commission_amount'],
            "unique_id"=> $first_data['unique_id'],
            "user_id"=> $first_data['user_id'],
            "avatar"=> $first_data['avatar'],
            "nickname"=>$first_data['nickname'],
            "create_time"=> $first_data['create_time'],
            "start_time"=> $first_data['start_time'],
            "end_time"=> $first_data['end_time'],
            "title"=> $first_data['title'],
            "type"=> "baoliao",
            "qb_product_id"=> $first_data['product_id'],
            "platform"=> $first_data['platform_name'],
            "class"=> 1
            
        ];

        return $baoliao_hb;
        //dd($baoliao_hb);


    }
    //爆料详情方案
    public function dataDetailfangan($request,$data=[])
    {
        #class =1 爆料  2.调用其他详情  3. guanggaung

        //用户id
        $people_id=$data['people_id'];
        if($people_id){
            $userlist=$this->userService->update_user($people_id);
            $levelId=$userlist['levelId'];  
        }else{
            $levelId=2;
        }

        //平台
        $platform_name=$data['platform_name'];

        //补贴
        $platformslist=$this->platformsService->getList();


        $product_id=$data['product_id'];
        $platform_name=$data['platform_name'];

        $where = [
            ['product_unique_id','=',$product_id],
            ['platform_name','=',$platform_name],
/*            ['create_time', '>=', date('Y-m-d H:i:s', strtotime('-3 days'))]*/

        ];



/*        $where1 = [
            ['product_unique_id','=','3TYrKwS9H8mjfZBSzt'],
            ['platform_name','=','京东'],

        ];*/
        //dd($where);
        #过期不过过期是根据开始时间和结束时间  ，如果过期还是用ai
        //$this->getLastSql();
        $list = $this->model->where($where)->select(['unit_price','publish_time','commission_rate','commission_amount','unique_id','user_id','avatar','nickname','create_time','start_time','end_time','title'])->get()->toArray();
        #优惠方案
        $promotion_plan=[];
        $baoliao_content=[];
        $is_expired=2;#默认不过期
        $is_expired2=false;#默认不走不过期
        foreach($list as $k=>$v){
            $v['type']='baoliao';
            # 发布时间
            $publish_time= $v['publish_time'];
            $day_3=date('Y-m-d H:i:s', strtotime('-3 days'));
            $v['qb_product_id']=$request->input("unique_id");
            $v['platform']=$platform_name;
            $v['class']=1;
            $v['user_id']=$people_id;
            if($publish_time>=$day_3){
                #判断是否过期
                #获取当前时间
                $currentTime =  time();
                //dd($v['end_time']);

                // 判断是否显示警告
                if ($currentTime >= strtotime($v['start_time']) && 
                    $currentTime <= strtotime($v['end_time'])){
                    #未过期
                    $is_expired2=true;
                    $is_expired=2;#默认不过期
                }else{
                    $unique_id=$v['unique_id'];
                    $data3=[];
                    $data3['create_time'] =date("Y-m-d H:i:s");
                    $data3['is_expired'] =1;//过期

                    $is_expired=1;//过期
                    $this->model->where(['unique_id'=>$unique_id])->update($data3);
                }


                $promotion_plan[]=$v;
           }
           $baoliao_content[]=$v;
        }
        //dd($baoliao_content);
        if($is_expired2){
            $is_expired=2;
        }
        #如果爆料数据三天内没有数据则也使用ai
        if(empty($promotion_plan)){
            $is_expired=1;
        }
        //dd($is_expired);
        $getinfo_url=$this->getInfo;
        $user_params=[
            "product_id"=>$request->input("unique_id"),
            "platform"=> $platform_name,
            "user_id"=> $people_id

        ];
        
        $userai_data=[];
        $postdata=json_post($getinfo_url,$user_params);
        //dd($postdata);
        $qb_product_id=$request->input("unique_id");

        #提示语
        $pingtai_name="";
        $yong_jin="0.00";
        $bu_tie="0.00";
        $jd_plus_commission_desc="";
        $user_data=[];


        #post 表参数
        $shop_id_post = 0;
        $title_post = '';
        $platform_post = '';
        // 商品描述和内容
        $content_post = '';

        // 图片相关
        $purchase_screenshots_post = [];
        $cover_post = '';
        $images_post = [];

        // 商品标识
        $product_id_post = $qb_product_id;
        $product_unique_id_post = '';

        // 价格信息
        $unit_price_post = '0.00';
        $origain_price_post = '0.00';
        $quantity_post = 1;

        // 佣金相关
        $commission_rate_post = '0.00';
        $commission_amount_post = '0.00';

        // 补贴相关（当前为空）
        $subsidy_rate_post = '0.00';
        $subsidy_amount_post = '0.00';
        $subsidy_name_post = '';
        $is_subsidy_post = '0';

        // 京东会员描述
        $jd_plus_commission_desc_post = '';

        // 分类信息
        $category_id_post = null;
        $category_name_post = '';

        // 优惠信息
        $purchase_youhuiquan_post = [];

        // 其他购买选项（当前为空数组）
        $purchase_huodong_post = [];
        $purchase_jiagou_post = [];
        $purchase_coudan_post = [];
        $original_brand_name='';
        $standard_brand_name='';
        $original_category_name='';
        $standard_category_name='';
        $publish_time_post=date('Y-m-d H:i:s');
        // 时间范围
        $start_time_post =date('Y-m-d H:i:s');
        $end_time_post = date('Y-m-d 23:59:59');
        #post 表参数结束

        $baoliao_hb=[];
        //获取用户详情数据 AI  
        if(isset($postdata['status'])&&$postdata['status']='200'){
            $user_data=$postdata['data'];
            #标题
            $name="";
            if(isset($user_data['name'])){
                $name=$user_data['name'];
                $title_post=$name;
            }
            #商品id
            if(isset($user_data['shop_id'])){
                $shop_id_post=$user_data['shop_id'];
            }
            #推荐方案
            //dd($user_data['steps_plan']);
            if(isset($user_data['steps_plan'])){
                $steps_plan=$user_data['steps_plan'];
                if(isset($steps_plan['duojian_step'])){
                     $duojian_step=$steps_plan['duojian_step'];
                     if(isset($duojian_step['price_desc'])){
                        $content_post=$duojian_step['price_desc'];
                     }
                     
                }

            }

            #优惠凭证
            if(isset($user_data['screen_img'])){
                $purchase_screenshots_post=$user_data['screen_img'];
            }

            #封面图片
            if(isset($user_data['img'])){
                $cover_post=$user_data['img'];
                $images_post[]=$user_data['img'];
            }

            #单价
            if(isset($user_data['final_price'])){
                 $unit_price_post=$user_data['final_price'];
            }

            #原价
            if(isset($user_data['origain_price'])){
                $origain_price_post=$user_data['origain_price'];
            }
            #佣金占比
            if(isset($user_data['commission_rate'])){
                $commission_rate_post=$user_data['commission_rate'];
            }
            #佣金金额
            if(isset($user_data['commission'])){
                $commission_amount_post=$user_data['commission'];
            }
            # 补贴相关（当前为空）
            $is_subsidy_post = 0;
            if(isset($user_data['platform_subsidy'])){
                
                $platform_subsidy=$user_data['platform_subsidy'];
                if(isset($platform_subsidy[0])){
                    $platform_subsidy=$platform_subsidy[0];
                    //dd($platform_subsidy['subsidy_rate']);
                    if(isset($platform_subsidy['subsidy_rate'])){
                       // dd($platform_subsidy);
                        $is_subsidy_post=1;
                        $subsidy_rate_post=$platform_subsidy['subsidy_rate'];

                    }
                    if(isset($platform_subsidy['subsidy_amount'])){
                        $subsidy_amount_post=$platform_subsidy['subsidy_amount'];
                    }

                    if(isset($platform_subsidy['subsidy_name'])){
                        $subsidy_name_post=$platform_subsidy['subsidy_name'];
                    }

                }
                
                ///dd($subsidy_amount);

            }

            // 京东会员描述
            if(isset($user_data['jd_plus_commission_desc'])){
                $jd_plus_commission_desc_post = $user_data['jd_plus_commission_desc'];
            }
            
            if(isset($user_data['original_category'])){
                $original_category_name=$user_data['original_category'];
            }

            if(isset($user_data['standard_category'])){
                $standard_category_name=$user_data['standard_category'];
                $category_name_post=$user_data['standard_category'];
            }
            if(isset($user_data['original_brand'])){
                $original_brand_name=$user_data['original_brand'];
            }
            if(isset($user_data['standard_brand'])){
                $standard_brand_name=$user_data['standard_brand'];
            }
            
            $steps_plan=$user_data['steps_plan'];
            $purchase_youhuiquan_post=[];
            if(isset($steps_plan['duojian_step']) && !empty($steps_plan['duojian_step']['coupon_list']))
            {
                //优惠券
                $coupon_list=$steps_plan['duojian_step']['coupon_list'];
                foreach($coupon_list as $k=>$v){
                    $purchase_youhuiquan_post[]=[
                        'type'=>1,
                        'title'=>'优惠券',
                        'description'=>$v['coupon_title'],
                        'link'=>$v['coupon_url'],
                        'platform'=>$user_params['platform'],
                    ];
                }

            }
            $purchase_huodong_post=[];
            if(isset($steps_plan['duojian_step']) && !empty($steps_plan['duojian_step']['discount_desc']))
            {
                //活动
                $discount_desc=$steps_plan['duojian_step']['discount_desc'];
                foreach($discount_desc as $k=>$v){
                    $purchase_huodong_post[]=[
                        'type'=>2,
                        'title'=>'活动',
                        'description'=>$v,
                        'link'=>'',
                        'platform'=>$user_params['platform'],
                    ];
                }


            }
            #后缀 
            if(isset($user_data['product_id_suffix'])){
                $product_unique_id_post=$user_data['product_id_suffix'];
            }




            //dd($name);
            ####提示####
            #从京东会员plus提示
            if(isset($user_data['jd_plus_commission_desc'])){
                $jd_plus_commission_desc=$user_data['jd_plus_commission_desc'];
            }
            $pingtai_name=$platform_name;
            $platform_post=$platform_name;
            #佣金
            if(isset($user_data['commission'])){
                $yong_jin=$user_data['commission'];
            }
            #补贴
            if(isset($user_data['other_rate'])){
                $other_rate=$user_data['other_rate'];

                if(isset($other_rate['subsidy_rate'])){
                    $bu_tie=$other_rate['subsidy_rate'];
                }
                
            }

            $estimate_commission=$user_data['commission_rate'];
            #预估返
            if(isset($user_data['estimate_commission'])){
                $estimate_commission=$user_data['estimate_commission'];
                //dd($estimate_commission);
            }
            


           // dd($bu_tie);
            //$people_id=
            $user=$this->userService->update_user($people_id);
            

            #存储第一次用户id
            $hdata=[
                'unique_id'=>"{$product_id},{$platform_name}",
                'platform_name'=>$platform_name,
                'product_id'=>$qb_product_id,
                'estimate_commission'=>$estimate_commission,
                'json_data'=>json_encode($user_data, JSON_UNESCAPED_UNICODE)
            ];
            ///dd($hdata);
            $ar=platform_name_product_id($platform_name,$hdata['product_id']);
            $hdata['product_unique_id']=$ar['1'];
            # 获取发布时间
            $ai_arr=$this->postaiService->addData($request,$hdata);
            $publish_time=$ai_arr['publish_time'];
     /*       "product_id": "E9f2MHlFDPtE4i9RwfDfWoL4LIVEcaVgAw_JQaQAPu9IU",
            "platform": "PDD",
            "user_id": "1227"*/
            $publish_time_post=$publish_time;
            $userai_data[]=[
                "type"=>'baoliao',
                "title"=>$name,
                "class"=>2,
                "unit_price"=>$user_data['final_price'],
                "commission_rate"=>$user_data['commission_rate'],//改成预估返回
                'commission_amount'=>$estimate_commission,
                'unique_id'=>"{$qb_product_id},{$platform_name}",
                'user_id'=>$people_id,
                'qb_product_id'=>$qb_product_id,
                'platform'=> $platform_name,
                'publish_time'=>$publish_time,
                'avatar'=>"http://xingfanapp.oss-cn-hangzhou.aliyuncs.com/xingfanapp/uploads/442ca8601a70923b7fdb5d697188f80c3983df5c.png",
                'nickname'=>"乐天未来"
            ];
        }
        
        //dd($userai_data);
        #优惠方案
        $plan_fangan=[];
        //dd($is_expired);
        # 如果过期就合并ai
        if($is_expired==1){
            #日期过期生成一个新的ai
            $data_baoliao_post = [
                'avatar' => 'http://xingfanapp.oss-cn-hangzhou.aliyuncs.com/xingfanapp/uploads/442ca8601a70923b7fdb5d697188f80c3983df5c.png',
                'nickname' => '乐天未来',
                'product_id'=>$product_id_post,
                'article_title'=>$title_post,
                'shop_id' => $shop_id_post,
                'title' => $title_post,
                'platform' => $platform_post,
                'publish_time'=>$publish_time_post,
                'product_unique_id'=>$product_unique_id_post,
                'images'=>$images_post,
                'type' => '5',
                'user_id' => '633',
                'content' => $content_post,
                'purchase_screenshots' => $purchase_screenshots_post,
                'cover' => $cover_post,
                'unit_price' =>$unit_price_post,
                'subsidy_rate' => $subsidy_rate_post,
                'subsidy_amount' => $subsidy_amount_post,
                'subsidy_name' => $subsidy_name_post,
                'is_subsidy' => $is_subsidy_post,
                'jd_plus_commission_desc' => $jd_plus_commission_desc_post,
                'quantity' => $quantity_post,
                'images' => $images_post,
                'category_id' => null,
                'category_name' => $category_name_post,
                'origain_price' => $origain_price_post,
                'commission_rate' => $commission_rate_post,
                'commission_amount' => $commission_amount_post,
                'product_unique_id' => $product_unique_id_post,
                'purchase_youhuiquan' => $purchase_youhuiquan_post,
                'purchase_huodong' => $purchase_huodong_post,
                'purchase_jiagou' => $purchase_jiagou_post,
                'purchase_coudan' => $purchase_coudan_post,
                'start_time' => $start_time_post,
                'end_time' => $end_time_post,
                'original_brand_name'=>$original_brand_name,
                'standard_brand_name'=>$standard_brand_name,
                'original_category_name'=>$original_category_name,
                'standard_category_name'=>$standard_category_name,
                'brand_name'=>$standard_brand_name
            ];
            //dd($data_baoliao_post);
            $baoliao_hb=$this->perfectInfoParms3($request,$data_baoliao_post);

            #爆料合并
            //$baoliao_hb=[];
            


            $plan_fangan=array_merge($promotion_plan,$userai_data);
        }else{
            $plan_fangan=$promotion_plan;
        }
        
        $plan_fangan=array_values($plan_fangan);
        $datag=[
            'unique_id'=>"{$product_id},{$platform_name}",
            'is_expired'=>$is_expired
        ];
        //dd($datag);
        #关于内容-相关内容
        //$postai=$this->postaiService->getList($request,$datag);
        /*if(!empty($postai)){
            $baoliao_content=array_merge($baoliao_content,$postai);
            
        }*/
        if(!empty($baoliao_hb)){
            $baoliao_content=array_merge($baoliao_content,$baoliao_hb);
        }
        $baoliao_content=array_values($baoliao_content);
        //dd($baoliao_content);

        $guangguang_list=$this->doubanpostproduct->where($where)->select(['unit_price','commission_rate','commission_amount','unique_id','user_id','avatar','nickname','create_time','publish_time','post_unique_id','title'])->get()->toArray();
        $guangguang_day3=[];
        foreach($guangguang_list as &$v){
            $v['type']='guangguang';
            $publish_time=$v['publish_time'];
            $day_3=date('Y-m-d H:i:s', strtotime('-3 days'));
            $v['class']='3';
            $v['commission_rate']=$v['commission_rate']/100;
            if($publish_time>=$day_3){
                $guangguang_day3[]=$v;
            }

        }
        $guangguang_content=$guangguang_list;
        #去重
        /*$fields=['unit_price','commission_amount'];
        $baoliao_content=arrayUniqueByFields($baoliao_content, $fields); */
        //dd($baoliao_content);
        #相关内容
        $about_content=[
            'baoliao_content'=>$baoliao_content,
            'guangguang_content'=>$guangguang_content,
        ];
        //dd($about_content['baoliao_content']);
        $baoliao_day3=$plan_fangan;
        #爆料去重
   /*     $fields=['unit_price','commission_amount'];
        $baoliao_day3=arrayUniqueByFields($plan_fangan, $fields); */
        #优惠方案
        $promotion_plan=[
            'plan_fangan'=>$plan_fangan,
            'baoliao_day3'=>$baoliao_day3,
            'guangguang_day3'=>$guangguang_day3,
            
        ];

/*        if($data['id']){
             //用户id
            $id=$data['id'];
            $doubanpost_first=$this->doubanpost->where(['id'=>$id])->first();
            if($doubanpost_first){
                $first=$this->doubanpostproduct->where(['post_unique_id'=>$doubanpost_first['unique_id']])->first();
                $subsidy_rate=$first['subsidy_rate'];
                $commission_rate=$first['commission_rate'];
                $pingtai_name=$first['subsidy_name'];
                $yong_jin=$first['commission_amount'];
                $bu_tie=$first['subsidy_amount'];
                if(empty($bu_tie)){
                    $bu_tie=0.00;
                }
                $unit_price=$first['unit_price'];
                $jd_money=get_jd_money($subsidy_rate,$commission_rate,$levelId,$platform_name,$unit_price);
                $estimate_commission=$jd_money['estimate_commission'];
                //dd($jd_money);
                $jd_plus_commission_desc="如是京东Plus账号，下单佣金约为{$estimate_commission}";
            }
        }*/

        if($bu_tie==0){
            $bu_tie_msg='';
        }else{
            $bu_tie_msg="该商品参与{$pingtai_name}活动(佣金{$yong_jin}) (补贴{$bu_tie})";
        }
        $result=[];
        $result=[
            'bu_tie_msg'=>$bu_tie_msg,
            'jd_plus_commission_desc'=>$jd_plus_commission_desc,
            'promotion_plan'=>$promotion_plan,
            'about_content'=>$about_content,
        ];

        return $result;



    }

    //方案详情
    public function baoliaoDetailfangandefault($request,$data=[])
    {
        $class=$data['class'];
        $unique_id=$data['unique_id'];
        $people_id=$data['people_id'];
        $list=[];
        if($class=='1'){
            $data1=[
                'unique_id'=>$unique_id,
                'people_id'=>$people_id,
            ];
            $list=$this->dataDetail($request,$data1);
            //dd($list);

        }else if($class=='2'){
            $ar=explode(',',$unique_id);
            $getinfo_url=$this->getInfo;
            $user_params=[
                "product_id"=>$ar[0],
                "platform"=> $ar[1],
                "user_id"=> $people_id

            ];
            # 测试
/*            $user_params=[
                "product_id"=>'GKaQqo52S8tYdPp5XJnFvXPiQtJ-36Mr07wH0Oe7Orgxsqy',
                "platform"=> '淘宝',
                "user_id"=> $people_id

            ];*/
            $postdata=json_post($getinfo_url,$user_params);
            if($postdata['status']='200'){
                $user_data=$postdata['data'];
                $user=$this->userService->update_user($people_id);
                $steps_plan=$user_data['steps_plan'];
                //dd($steps_plan);
                $purchase_youhuiquan=[];
                if(isset($steps_plan['duojian_step']) && !empty($steps_plan['duojian_step']['coupon_list']))
                {
                    //优惠券
                    $coupon_list=$steps_plan['duojian_step']['coupon_list'];
                    foreach($coupon_list as $k=>$v){
                        $purchase_youhuiquan[]=[
                            'type'=>1,
                            'title'=>'优惠券',
                            'description'=>$v['coupon_title'],
                            'link'=>$v['coupon_url'],
                            'platform'=>$user_params['platform'],
                        ];
                    }

                }
                $purchase_huodong=[];
                if(isset($steps_plan['duojian_step']) && !empty($steps_plan['duojian_step']['discount_desc']))
                {
                    //活动
                    $discount_desc=$steps_plan['duojian_step']['discount_desc'];
                    foreach($discount_desc as $k=>$v){
                        $purchase_huodong[]=[
                            'type'=>2,
                            'title'=>'活动',
                            'description'=>$v,
                            'link'=>'',
                            'platform'=>$user_params['platform'],
                        ];
                    }


                }

                $content='';
                if(isset($steps_plan['duojian_step']) && !empty($steps_plan['duojian_step']['price_desc']))
                {
                    //推荐方案
                    $content=$steps_plan['duojian_step']['price_desc'];
                    

                }



            $purchase=[];
            $purchase_steps=[];
            //dd($purchase_huodong);

            if(!empty($purchase_youhuiquan)){
                $purchase_steps=array_merge($purchase,$purchase_youhuiquan);
            }
            if(!empty($purchase_huodong)){
                $purchase_steps=array_merge($purchase_steps,$purchase_huodong);
            }
            /*if(!empty($purchase_jiagou)){
                $purchase_steps=array_merge($purchase_steps,$purchase_jiagou);
            }
            if(!empty($purchase_coudan)){
                $purchase_steps=array_merge($purchase_steps,$purchase_coudan);
            }*/

            //dd($purchase_steps);
            $quantity=1;

            $data=$list = [
                "id" => $unique_id,
                "unique_id" => $unique_id,
                "purchase_steps" =>$purchase_steps,
                "purchase_screenshots" =>[],
                "title" => $user_data['name'],
                "images" => $user_data['screen_img'],
                "avatar" => 'http://xingfanapp.oss-cn-hangzhou.aliyuncs.com/xingfanapp/uploads/442ca8601a70923b7fdb5d697188f80c3983df5c.png',
                "nickname" => '乐天未来',
                "cover" => $user_data['img'],
                "begin_time" => '',
                "content" => $content,
                "create_time" => date("Y-m-d H:i:s"),
                "update_time" => date("Y-m-d H:i:s"),
                "unit_price" =>$user_data['final_price'] ,
                "quantity" => $quantity,
                "final_price" => $user_data['final_price'] ,
                "commission_rate" => $user_data['commission_rate'],
                "commission_amount" => $user_data['commission'],
                "commission_amount_total" => $user_data['commission'],
                "product_id" => $user_data['product_id'],
                "product_unique_id" => $user_data['product_id_suffix'],
                "user_id" => $people_id,
                "platform_name" => $ar[1],
                'start_time'=>'',
                'end_time'=>'',
                'publish_time'=>date("Y-m-d H:i:s")
            ];


            $platform_name=$data['platform_name'];
            //活动，优惠，加购，凑单，下单
            $purchase_steps=$data['purchase_steps'];

            #组装数据
            foreach ($purchase_steps as $k=> &$v) {
                switch ($v['type']) {
                    case '1':
                        $v['data-dimension122']="优惠券";
                        $v['tag_text']=$v['description'];
                        $v['you_hui_tiao_zhuan_link_end']='';
                        $v['huo_dong_time']='';
                        break;
                    case '2':
                        if(isset($v['link'])&&empty($v['link'])){
                            //unset($purchase_steps[$k]);
                        }else{
                            $v['data-dimension122']="活动";
                            $v['tag_text']=$v['description'];
                            $v['you_hui_tiao_zhuan_link_end']='';
                            $v['huo_dong_time']='';
                        }
                        
                        break;
                    case '3':
                        $v['data-dimension122']="加购";
                        $v['tag_text']=$v['description'];
                        $v['you_hui_tiao_zhuan_link_end']='';
                        $v['huo_dong_time']='';
                        break;
                    case '4':
                        $v['data-dimension122']="凑单";
                        $v['tag_text']=$v['description'];
                        $v['you_hui_tiao_zhuan_link_end']='';
                        $v['huo_dong_time']='';
                        break;
                    default:
                }


            }
            if(!isset($this->URL_MAP[$platform_name])){
                $this->error("平台不存在,请联系管理员添加平台[{$platform_name}]");
            }

            $url=$this->URL_MAP[$platform_name];
            $productId=$data['product_id'];
            $platform =$data['platform_name'];
            $final_price=$data['final_price'];
            $commission_amount_total =$data['commission_amount_total'];
            //是否是产品
            $fetch_platform_data=fetch_platform_data($platform_name,$productId,$url);
            $is_product=1;
            $product_list=[];
            if($fetch_platform_data){
                $product_list[]=[
                    'type'=> 'link',
                    'text'=> $fetch_platform_data['productUrl'],
                    'title'=> $fetch_platform_data['title'],
                    'productImage'=> $fetch_platform_data['productImage'],
                    'productName'=> $fetch_platform_data['productName'],
                    'product_id'=> $fetch_platform_data['item_id'],
                    'platform_name'=> $platform,
                    'link_text'=> '',
                ];

            }else{
                $is_product=0;
            }
            $link="";
            if(!empty($product_list)){
                $link=$product_list[0]['text'];

            }

            //dd($data['product_list']);
            //加购
            $purchase_steps[]=[
                "data-dimension122"=> "加购",
                "type"=>3,
                "tag_text"=> "下单{$quantity}件-{$data['title']}",
                "you_hui_tiao_zhuan_link_end"=> "",
                "huo_dong_time"=> null,
                "platform"=>$platform_name,
                "title"=> "加购",
                "description"=> "下单{$quantity}件-{$data['title']}",
                "link"=>$link,

            ];
            //$quantity=1;
            //下单
            if($quantity>1){

                $lastunitPrice = $unit_price-$commission_amount;
                //dd($commission_amount);
                //$shifu=$unit_price*$quantity;
                $lastunitPrice =_round($lastunitPrice);
                $purchase_steps[]=[
                    "data-dimension122"=> "下单",
                    "title"=> "下单",
                    "type"=> 5,
                    "description"=> "下单{$quantity}件实付{$final_price}，下单后返利约{$commission_amount_total}元，单价合{$lastunitPrice}元",
                    "link"=>'',
                    "platform"=>'',
                ];
            }else{
                $purchase_steps[]=[
                    "data-dimension122"=> "下单",
                    "type"=> 5,
                    "title"=> "下单",
                    "description"=> "实付{$final_price}，下单后返利约{$commission_amount_total}元",
                    "link"=>'',
                    "platform"=>'',
                ];
            }
           // dd($purchase_steps);
            $list['purchase_steps']=array_values($purchase_steps);

        }


        }else{
            //逛逛
            $data1=[
                'unique_id'=>$unique_id,
                'people_id'=>$people_id,
            ];
            $list=$this->DoubanpostproductService->dataDetail($request,$data1);



        }
        return $list;
    }

    
    //爆料详情
    public function dataDetail($request,$data=[])
    {
        //用户id
        $people_id=$data['people_id'];
        if($people_id){
            $userlist=$this->userService->update_user($people_id);
            $levelId=$userlist['levelId'];  
        }else{
            $levelId=2;
        }



        //补贴
        $platformslist=$this->platformsService->getList();


        $unique_id=$data['unique_id'];

        $where = [
           ['unique_id','=',$unique_id],
        ];
        //
        $list = $this->model->where($where)->select(['id','unique_id','purchase_steps','purchase_screenshots','title','images','avatar','nickname','cover','begin_time','content','create_time','update_time','unit_price','quantity','final_price','commission_rate','commission_amount','commission_amount_total','product_id','product_unique_id','user_id','platform_name','start_time','end_time','publish_time','like_count','collect_count','comment_count','view_count','sales_count'])->first();
        if(empty($list)){
            $this->error("没有数据");
        }

        $likeList=Baoliaolike::getList();
        $collectList=Baoliaocollect::getList();
        //dd($collectList);
        $key="{$list['unique_id']}_{$people_id}";

        $list['is_like'] =2;
        if(isset($likeList[$key])){
            $list['is_like'] =1;
        }
        $list['is_collect'] =2;
        if(isset($collectList[$key])){
            $list['is_collect'] =1;
        }



        $list['purchase_steps'] =json_decode($list['purchase_steps'],true);


        $list['purchase_screenshots'] =json_decode($list['purchase_screenshots'],true);
        
        return $list;
    }
    //爆料佣金计算
/* * 计算展示给用户的佣金
 * @param float $amount 实际付款金额
 * @param float $commissionRate 佣金比例（如0.05表示5%）
 * @param float $subsidyRate 补贴比例（如0.02表示2%）
 * @param string $platform 平台标识（taobao/jd/pdd）
 * @param string $grade 用户等级（星粉/星光/星辰）
 * @return float 最终展示的佣金金额（保留两位小数）
 * @return is_owner 京东非自营
 * */
public function calculateDisplayCommission(float $amount,float $commissionRate,float $subsidyRate,string $platform,string $levelId,string $is_owner): float {

    dd($is_owner);


    // 计算平台扣除比例
  /*  $platformDeduction = match ($platform) {
        '淘宝' => 0.89,  // 扣除11%
        '京东', '拼多多' => 0.99,  // 扣除1%
        default =>0.00

    };

    // 计算用户等级比例
    $gradeRatio = match ($levelId) {
        '1' => 0.94,
        '2' => 0.96,
        '3' => 1.00,
        default =>0.00
    };
  /*  if($platformDeduction==0.00){
        dd($platform);

    }*/

    // 计算最终佣金（保留两位小数）
    $finalCommission = $total * $subsidyRate * $gradeRatio;
    return _round($finalCommission, 2);
}

    //爆料-列表
    public function getList($request,$data=[])
    {
        //用户id
        $people_id=$data['people_id'];
        if(empty($people_id)){
            $levelId=2;//默认星光
        }else{
            $userlist=$this->userService->update_user($people_id);
            $levelId=$userlist['levelId'];
        }

        // 获取排序类型
        $unit_type = $data['unit_type'] ?? 1;


        //补贴
        $platformslist=$this->platformsService->getList();



        $where=" where 1=1";
        if($data['content']){
            $content=$data['content'];
            $where.="  and  CONCAT(
                    COALESCE(title, ''), 
                    COALESCE(content, ''), 
                    COALESCE(y_content, ''), 
                    COALESCE(category_name, '')
                )  like '%{$content}%'";

        }

        #最新=2
        if($unit_type==2){
            $where.="  and  is_expired = '2'";
        }
        # 1 首页   2. 个人
        if($people_id && $data['type']=='2'){
            $where.="  and  user_id = '{$people_id}'";
        }
        # 分类
        if(isset($data['name'])){
            if(!empty($data['name'])){
                $category_name=$data['name'];
                $where.="  and  category_name like '%{$category_name}%' ";
            }

        }
        //$where.="  and  id = '10829'";

        // 使用参数化查询防止SQL注入
        $sql = "SELECT `id`, `create_time`,`update_time`, `is_owner`,`purchase_steps`, `type`, `unique_id`, `platform_name`, `title`, 
               `cover`, `unit_price`, `quantity`, `final_price`, `view_count`, `commission_rate`, 
               `comment_count`, `collect_count`, `sales_count`, `commission_amount`, `publish_time` , `product_id`,`subsidy_rate`,`user_id`
        FROM `module_baoliao_post` 
        {$where} 
        ORDER BY publish_time DESC, id DESC  limit 5000";

        //die($sql);
        $list = DB::select($sql);
        $list = array_map('get_object_vars', $list);

        //dd($list);
        foreach ($list as $k=> &$content) {

            // title  值选替换星选
            $content['title'] = str_replace('值选', '星选',$content['title']);
            #时间重写--某傻逼用错字段
            $content['create_time']=$content['publish_time'];
            $content['update_time']=$content['publish_time'];
           // dd($content['create_time']);
            $final_price=$content['final_price'];
            if(empty($final_price)){
                $final_price=0;
                $content['final_price']=$final_price;
            }
            //实际佣金
            $unit_price=$content['unit_price'];
            if(empty($unit_price)){
                $unit_price=0;
                $content['unit_price']=$unit_price;
            }
            //平台标识
            $platform=$platform_name=$content['platform_name'];
            //dd($platform_name);
/*             * @param float $amount 实际付款金额
             * @param float $commissionRate 佣金比例（如0.05表示5%）
             * @param float $subsidyRate 补贴比例（如0.02表示2%）
             * @param string $platform 平台标识（taobao/jd/pdd）
             * @param string $grade 用户等级（星粉/星光/星辰）
             * @return float 最终展示的佣金金额（保留两位小数）*/
            
            # 佣金占比
  /*          $commissionRate=$content['commission_rate']/100;

            if(isset($platformslist[$platform_name])){
                $subsidyRate=$platformslist[$platform_name]['reserve_rate'];
            }else{
                unset($list[$k]);
            }*/

            //dd($unit_price);
/*            $is_owner=$content['is_owner'];
            $commission_amount=$this->calculateDisplayCommission($unit_price,$commissionRate,$subsidyRate,$platform,$levelId,$is_owner);
            dd($commission_amount);

            $content['commission_amount']=$commission_amount;*/

            //dd($content['commission_amount']);

            $view_count=$content['view_count'];
            if(empty($view_count)){
                $view_count=0;
                $content['view_count']=$view_count;
            }
            $comment_count=$content['comment_count'];
            if(empty($comment_count)){
                $comment_count=0;
                $content['comment_count']=$comment_count;
            }
            $collect_count=$content['collect_count'];
            if(empty($collect_count)){
                $collect_count=0;
                $content['collect_count']=$collect_count;
            }
            $sales_count=$content['sales_count'];
            if(empty($sales_count)){
                $sales_count=0;
                $content['sales_count']=$sales_count;
            }
            $content['base_score'] = ContentScoringService::calculateReportScore(
                $final_price,
                $unit_price,
                $view_count,
                $comment_count,
                $collect_count,
                $sales_count
            );
            $timestamp = strtotime($content['publish_time']); 
            #$content['publish_time']=date('m-d H:i',$timestamp);
            $content['days_passed'] = (time() - $timestamp) / 86400; // 计算天数
        }

        $unit_type=$data['unit_type'];
        switch ($unit_type) {
            case "1":
                //综合（按最终得分排序）
                $sortedBy = ContentScoringService::sortContents($list, 'comprehensive');
                break;
            case "2":
                // 最新（按发布时间降序）
                $sortedBy = ContentScoringService::sortContents($list, 'latest');
                break;
            case "3":
                // 最热（按浏览量降序）
                $sortedBy = ContentScoringService::sortContents($list, 'hottest');               
                break; 
             case "4":
                // 高佣金（按佣金降序）
                $sortedBy = ContentScoringService::sortContents($list, 'high_commission');           
                break; 
             case "5":
                // 高销量（按销量降序）
                $sortedBy = ContentScoringService::sortContents($list, 'high_sales');             
                break;
            default:
                //die($sql);
                $sortedBy =$list;
        }
    
        // 处理游标分页
        $total_count = count($sortedBy);
        $cursor = $request->input('cursor') ?? null;
        $limit = min(max((int)($request->input('limit') ?? 20), 1), 50);
        $start_index = 0;
        if ($cursor) {
            foreach ($sortedBy as $index => $item) {
                if ($item['id'] == $cursor) {
                    $start_index = $index + 1;
                    break;
                }
            }
        }
        //dd(count($list));
        $list= array_slice($sortedBy, $start_index, $limit);


  /*      foreach ($list as $k=>&$val)
        {
            if(empty($val['unit_price'])){
                $unit_price=0.00;
            }
            if(empty($val['subsidy_rate'])){
                $subsidy_rate=0.00;
            }
            if(empty($val['commission_rate'])){
                $commission_rate=0.00;
            }

            
            $subsidy_rate=$val['subsidy_rate']/100;
            $commission_rate=$val['commission_rate']/100;
            $people_id=$val['user_id'];
            //平台标识
            $platform=$platform_name=$val['platform_name'];

            #总佣金
            $moneylist=$this->moneyService->estimatedTotalCommission($unit_price,$subsidy_rate,$commission_rate,$platform,$people_id);
            #dd($moneylist);
            $val['commission_amount']=$moneylist['total_commission'];
            #保留两位小数
            $val['commission_amount']=_round($val['commission_amount']);

        }*/


        // 生成下一个游标
        $next_cursor = null;
        $has_more = ($start_index + $limit) < $total_count;
        //dd($has_more);
        if ($has_more && !empty($list)) {
            //dd($list);
            $last_product = end($list);
            $next_cursor = $last_product['id']; // 使用ID作为游标
        }

        $count = count($sortedBy);

        $result = [
            'data' => $list,
            'pagination' => [
                'has_more' => $has_more,
                'next_cursor' => $next_cursor,
                'limit' => $limit,
                'unit_type' => $unit_type,
                'total_count' =>$count
            ]
        ];
        return $result; 

    }
   
    /**
     *
     * @param array $params
     * @return array
     */
    public function addData1($request,$data_params=[])
    {
       
       $url=$this->url;
       $getinfo_url=$this->getInfo;
       $data1=[
            'content'=>$data_params['content']
       ];
       //dd($url);
       $result=[];
       $postdata=json_post($url,$data1);
       $items=$postdata['data']['items'];
       
       foreach($items as $v){
            $data=[];
            $success=$v['success'];
            if($success){
                $matchedPlatforms=$v['matchedPlatforms'];
                //dd($matchedPlatforms);
                foreach($matchedPlatforms as $v1){
                    if(!isset($v1['result'])){
                        continue;
                    }
                    $type=$v1['result']['type'];
                    //dd($type);
                    //type =3活动 1商品
                    if($type=='1'){
                        $productInfo=$v1['result']['productInfo'];
                        $data=[
                            'platform'=>$productInfo['platformName'],
                            'product_id'=>$productInfo['productId'],
                            'user_id'=>$data_params['user_id'],
                        ];
                        $result[]=$data;
                    }

                    
                }
                
            }
           
       }
       $request_detail=[];
       foreach($result as $v){
            //dd($v);
            $postdata=json_post($getinfo_url,$v);
            if($postdata['status']=='200'){
                $request_detail[]=$postdata['data'];
            }
       }
       if(count($request_detail)<1){
            $this->error("不能解析");
       }else{
            #获取原始分类
            $original_category="";
            $standard_category_name="未知";
            if(!empty($request_detail)){
                $shuju=$request_detail[0];
                if(isset($shuju['original_category'])){
                    $original_category=$shuju['original_category'];
                    $standard_category_name=$this->categorymappingService->targetCategory($original_category);
                }
                
                

               // dd($original_category);
            }

            #获取原始品牌

            $original_brand="";
            $standard_brand_name="未知";
            if(!empty($request_detail)){
                $shuju=$request_detail[0];
                if(isset($shuju['original_brand'])){
                    $original_brand=$shuju['original_brand'];
                    $standard_brand_name=$this->brandmappingService->targetBrand($original_brand);
                }
                
                

               // dd($original_category);
            }


            $request_detail[0]['standard_category_name']=$standard_category_name;
            $request_detail[0]['standard_brand_name']=$standard_brand_name;
            //dd($request_detail);
            return $request_detail;
       }
       
     

    }
   
}
